const { Add, Update, QueryOne, ExecGetOne, Exec } = require('../db/dbhelper');
var { init, format } = require('../models/active');
var { formatDateYear, formatDateTime } = require('../libs/common');
var _ = require('underscore');
const logger = require('../libs/log').logger;

// 创建活动
async function activeAdd(doc) {
  try {
    let isdone = await QueryOne('hzz_actives', { title: doc.title });
    if (isdone) {
      return {
        code: 1,
        msg: '已存在此名称活动，不能重复创建'
      }
    } else {
      doc.date_begin = new Date(doc.date_begin);
      doc.date_end = new Date(doc.date_end);
      await Add('hzz_actives', init(doc));
      return {
        code: 0,
        msg: '活动已创建'
      }
    }
  } catch (error) {
    logger.error('-----activeAdd----创建活动异常,请联系管理员,error', error)
    return {
      code: 1,
      msg: '创建活动异常,请联系管理员'
    }
  }
}
// 活动列表
async function activeList(doc) {
  try {
    let { pagenum, pagesize, pcode } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = `SELECT * FROM hzz_actives `;
    sql += ' ORDER BY createtime DESC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let list = await Exec(sql);

    // 查询此用户这些活动的状态
    let activeids = _.pluck(list, 'id') || [];
    let orderlist = [];
    if (activeids && activeids.length) {
      orderlist = await Exec(`select * from hzz_orders where pcode = '${pcode}' AND activeid IN (${activeids.join(',')})`);
    }
    logger.info('activeList',JSON.stringify(orderlist))

    list = _.map(list, function (item) {
      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);

      let porder = _.find(orderlist, (or) => {
        return or.activeid == item.id;
      });
      logger.info('item',item.id)
      logger.info('porder',porder)
      item.paystatus = porder ? porder.paystatus : -1;
      item.signstatus = porder ? porder.signstatus : 0;
      item.auditstatus = porder ? porder.auditstatus : 0;
      return item;
    });

    let total = (await ExecGetOne(`SELECT count(1) as total FROM hzz_actives `)).total;
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagenum,
        pagesize,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.info('-----active--activeList--活动列表异常,', error)
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}
// 活动列表-后台
async function activeListBack(doc) {
  try {
    let { pagenum, pagesize, title } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = `SELECT * FROM hzz_actives `;
    let sqlFilter = '';
    if (title) {
      sqlFilter += `  where title like '%${title}%' `;
    }
    sql += sqlFilter;
    sql += ' ORDER BY id DESC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let list = await Exec(sql);

    list = _.map(list, function (item) {
      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);
      return item;
    });

    let total = (await ExecGetOne(`SELECT count(1) as total FROM hzz_actives ` + sqlFilter)).total;
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagenum,
        pagesize,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    logger.info('-----active--activeList--活动列表异常,', error)
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

async function activeUpdate(doc) {
  logger.info('activeUpdate-----,',doc)
  if (doc.id) {
    let isdone = await ExecGetOne(`select * from hzz_actives where title='${doc.title}' and id<>${doc.id}`);
    if (isdone) {
      return {
        code: 1,
        msg: '活动修改失败，已存在此活动标题'
      }
    }
    let data_old = await ExecGetOne(`select * from hzz_actives where id=${doc.id}`);
    logger.info('activeUpdate-----,doc.price',doc.price+'---data_old,'+ JSON.stringify(data_old)+'sql:'+`select * from hzz_actives where id=${doc.id}`)
    if (doc.price != data_old.price) { // 金额有变动，校验是否有人创建过订单
      let isdone2 = await ExecGetOne(`select * from hzz_orders where activeid=${doc.id} and paystatus<>9`);
      if (isdone2) {
        return {
          code: 1,
          msg: '活动金额修改失败，已有人创建原金额订单'
        }
      }
    }
    if(doc.date_begin){
      doc.date_begin = new Date(doc.date_begin)
    }
    if(doc.date_end){
      doc.date_end = new Date(doc.date_end)
    }
    await Update('hzz_actives', format(doc));
    return {
      code: 0,
      msg: '活动修改成功'
    }
  } else {
    return {
      code: 1,
      msg: '活动修改失败，参数[id]缺失'
    }
  }
}

async function activeQueryone(doc) {
  try {
    if (!doc.id) {
      return {
        code: 1,
        msg: '参数缺失[id]'
      }
    }
    let result = {
      code: 0,
      data: {}
    };
    let data = await ExecGetOne(`select * from hzz_actives Where id=${doc.id}`);
    if (data) {
      data.createtime = formatDateTime(data.createtime);
      data.updatetime = formatDateTime(data.updatetime);
      data.date_begin = formatDateTime(data.date_begin);
      data.date_end = formatDateTime(data.date_end);
      result.data = data;
    } else {
      result = {
        code: 1,
        msg: '未找到活动'
      };
    }
    return result;
  } catch (error) {
    return {
      code: 1,
      msg: '请求异常，请联系客服'
    }
  }
}

module.exports = {
  activeAdd,
  activeUpdate,
  activeList,
  activeListBack,
  activeQueryone
}